package com.woniuxy.sale.controller;


import com.woniuxy.model.vo.GoodsVo;
import com.woniuxy.response.CustomPage;
import com.woniuxy.response.ResponseResult;
import com.woniuxy.model.entity.ExportTable;
import com.woniuxy.sale.entity.dto.SaleOrderDTO;
import com.woniuxy.sale.entity.dto.SalePackDTO;
import com.woniuxy.sale.entity.dto.TopDTO;
import com.woniuxy.sale.entity.vo.*;
import com.woniuxy.model.vo.UpdateSaleOrderVo;
import com.woniuxy.sale.exception.SaleOrderAddException;
import com.woniuxy.sale.service.SaleOrderService;
import com.woniuxy.sale.util.MyExcelUtils;
import com.woniuxy.util.CheckTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 选货单总表; 前端控制器
 * </p>
 *
 * @author lio
 * @since 2023-09-07
 */
@Slf4j
@RestController
@RequestMapping("/saleOrder")
public class SaleOrderController {

    @Resource
    private SaleOrderService saleOrderService;

    /**
     * 选货单详情页:仓库、[时间段]、[选货单号]、页码、页大小
     */
    @PostMapping("/info")
    public ResponseResult<CustomPage<List<SaleOrderDTO>>> info(@RequestBody SaleOrderVo saleOrderVo){
        log.info(saleOrderVo.toString());

        CustomPage<List<SaleOrderDTO>> page = saleOrderService.info(saleOrderVo);

        return new ResponseResult<>(ResponseResult.SUCCESS,"success",page);
    }

    /**
     *
     * 通过仓库、[商品编号]、[物料]、[品类]、[成色]查找状态为0的产品信息,仓库默认为1  带分页信息 弃用
     */
    @PostMapping("/findGoods")
    public ResponseResult<CustomPage<List<GoodsVo>>> findGoods(@RequestBody GoodsVo goodsVo){
        CustomPage<List<GoodsVo>> goodsList = saleOrderService.findGoods(goodsVo);
        return null;
    }

    /**
     * 新增选货单 仓库id、客户、商品id、数量
     */
    @PreAuthorize("hasAnyAuthority('sale:agreePack','sale:addPack')")
    @PostMapping("/add")
    public ResponseResult<Boolean> add(@RequestBody AddSaleOrderVo saleOrderVo, HttpServletRequest request)
            throws SaleOrderAddException {

        String aid = request.getHeader("access_token");
        Map<String,Object> user = CheckTokenUtil.getUser(aid);
        assert user != null;
        String creator = (String) user.get("account");
        saleOrderVo.setCreator(creator);

        return new ResponseResult<>(ResponseResult.SUCCESS,"success",saleOrderService.add(saleOrderVo));
    }

    /**
     * 修改选货单状态 sno state
     */
    @PostMapping("/updateState")
    public ResponseResult<Boolean> updateState(@RequestBody UpdateSaleOrderVo updateSaleOrderVo){

        if(saleOrderService.updateState(updateSaleOrderVo)){
            return new ResponseResult<>(ResponseResult.SUCCESS,"success",true);
        }
        return new ResponseResult<>(ResponseResult.UpdateSaleOrderState_ERROR,"fail",false);
    }

    /**
     * 删除选货单 sno 只有状态是0的能删除
     */
    @PreAuthorize("hasAnyAuthority('sale:agreePack','sale:addPack')")
    @PostMapping("/del")
    public ResponseResult<Boolean> del(@RequestBody DelSaleOrderVo delSaleOrderVo,HttpServletRequest request){

        String aid = request.getHeader("access_token");
        Map<String,Object> user = CheckTokenUtil.getUser(aid);
        assert user != null;
        String creator = (String) user.get("account");
        delSaleOrderVo.setCreator(creator);
        log.debug(delSaleOrderVo.toString());

        return new ResponseResult<>(ResponseResult.SUCCESS,"success",saleOrderService.del(delSaleOrderVo));
    }

    /**
     * 查看所有选货单产品库存状态,即[新增打包单页面]
     */
    @PostMapping("/packInfo")
    public ResponseResult<CustomPage<List<SalePackDTO>>> packInfo(@RequestBody SaleOrderVo saleOrderVo){
        log.info(saleOrderVo.toString());

        CustomPage<List<SalePackDTO>> page = saleOrderService.packInfo(saleOrderVo);

        return new ResponseResult<>(ResponseResult.SUCCESS,"success",page);
    }

    /**
     * 管理员审核
     */
    @PreAuthorize("hasAuthority('sale:agreePack')")
    @PostMapping("/check")
    //@PreAuthorize("hasAuthority('sale:agreePack')")
    public ResponseResult<Boolean> check(@RequestBody UpdateSaleOrderVo updateSaleOrderVo){
        if(saleOrderService.check(updateSaleOrderVo)){
            return new ResponseResult<>(ResponseResult.SUCCESS,"success",true);
        }
        return new ResponseResult<>(ResponseResult.UpdateSaleOrderState_ERROR,"fail",false);
    }

    /**
     * 查找所有的sno
     */
    @GetMapping("/findAllSno")
    public ResponseResult<List<String>> findAllSno(){
        return new ResponseResult<>(ResponseResult.SUCCESS,"success",saleOrderService.findAllSno());
    }

    /**
     * 导出成excel
     */
    @PreAuthorize("hasAnyAuthority('sale:agreePack','sale:addPack')")
    @PostMapping("exportSaleOrder")
    public void exportSaleOrder(@RequestBody SaleOrderVo saleOrderVo, HttpServletResponse response,HttpServletRequest request) {

        List<SaleOrderDTO> list = saleOrderService.info(saleOrderVo).getData();
        System.out.println(list.toString());
        log.debug(list.toString());
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));

        String aid = request.getHeader("access_token");
        Map<String,Object> user = CheckTokenUtil.getUser(aid);
        assert user != null;
        String account = (String) user.get("account");
        ExportTable table = new ExportTable();
        table.setAccount(account);
        table.setTableName("选货单");
        boolean flag = saleOrderService.exportSaleOrder(table);

        response.addHeader("Access-Control-Expose-Headers","exportFlag");
        response.addHeader("exportFlag",String.valueOf(flag));

        MyExcelUtils.exportExcel(list,
                "选货单",
                "选货单列表",
                SaleOrderDTO.class,
                "选货单"+time+".xls",response);
    }

    /**
     * 修改选货单
     */
    @PreAuthorize("hasAnyAuthority('sale:agreePack','sale:addPack')")
    @PostMapping("/updateSaleOrder")
    public ResponseResult<Boolean> updateSaleOrder(@RequestBody UpdateSaleOrderAllVo updateSaleOrderAllVo){

        return new ResponseResult<>(ResponseResult.SUCCESS,"success",
                saleOrderService.updateSaleOrder(updateSaleOrderAllVo));
    }

    /**
     * 当月已付定金销量前6的产品
     */
    @GetMapping("/findTopPaid")
    public ResponseResult<List<TopDTO>> findTopPaid(){
        return new ResponseResult<>(ResponseResult.SUCCESS,"success",saleOrderService.findTopPaid());
    }

    /**
     * 当月未付定金销量前6的产品
     */
    @GetMapping("/findToUnpPaid")
    public ResponseResult<List<TopDTO>> findToUnpPaid(){
        return new ResponseResult<>(ResponseResult.SUCCESS,"success",saleOrderService.findToUnpPaid());
    }

    /**
     * 通过sno查找选货单总价
     */
    @GetMapping("/findTotalPriceBySno/{sno}")
    public ResponseResult<BigDecimal> findTotalPriceBySno(@PathVariable("sno") String sno){
        log.debug("sno:" + sno);
        return new ResponseResult<>(ResponseResult.SUCCESS,"success",saleOrderService.findTotalPriceBySno(sno));
    }
}

